<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\CashInfo;
use Illuminate\Http\Request;

class CashInfosController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:user');
    }

    public function index(Request $request)
    {
        $info = $request->user('user')->cashInfo;
        return view('user.cash_infos.index', compact('info'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'cash_type' => ['required', 'in:' . implode(',', array_keys(CashInfo::$cashTypeMap))],
            'realname' => ['required'],
            'account' => ['required'],
        ], [
            'cash_type.required' => '请选择提现方式',
            'cash_type.in'       => '请选择正确的提现方式',
            'realname.required'  => '真实姓名不能为空',
            'account.required'   => '提现账号不能为空',
        ]);
        $data = $request->only(['cash_type', 'realname', 'account']);
        $cashInfo = $request->user('user')->cashInfo;
        if (is_null($cashInfo)) {
            CashInfo::create(array_merge(['user_id' => $request->user('user')->id], $data));
        } else {
            $cashInfo->cash_type = $data['cash_type'];
            $cashInfo->realname = $data['realname'];
            $cashInfo->account = $data['account'];
            $cashInfo->save();
        }
        return back()->with('success', '设置成功');
    }
}
